package com.daxia.bumall.web.controller.m;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daxia.bumall.common.SystemConfigType;
import com.daxia.bumall.common.ValidateCodeTypes;
import com.daxia.bumall.dto.ValidateCodeDTO;
import com.daxia.bumall.exception.BizException;
import com.daxia.bumall.util.DevUtils;
import com.daxia.bumall.util.SmsService;
import com.daxia.bumall.util.ValidationUtils;

@Controller
@RequestMapping(value = "/m/sms", produces="application/json;charset=UTF-8")
public class MSmsController extends MBaseController {

    @ResponseBody
    @RequestMapping("getValidateCode")
    public String getValidateCode(String mobile, Integer type, HttpServletRequest request) {
        ValidationUtils.assertTrue(type != null, "获取原因不能为空");
        ValidationUtils.assertTrue(StringUtils.isNotBlank(mobile), "手机号不能为空");
        ValidationUtils.validateMobile(mobile, "手机号码不合法");
        
        ValidateCodeDTO oldCode = validateCodeService.findByMobile(mobile);
        
        if (oldCode != null) {
            if (System.currentTimeMillis() - oldCode.getTime() < (60 * 1000)) {
                throw new BizException("获取验证码过于频繁");
            }
        }
        
        String sendSmsStr = systemConfigService.get(SystemConfigType.SendSms);
        boolean sendSms = "true".equalsIgnoreCase(sendSmsStr) || "1".equals(sendSmsStr);
        if (DevUtils.isTestServer()) {
        	sendSms = false;
        }
        int code = 888888;
        
        String msg = "";
        if (type == ValidateCodeTypes.Register.getValue()) { // 注册的
            // 验证手机号码是否已经被注册了
            if (userService.isMobileRegistered(mobile)) {
                throw new BizException("该手机号码已经被注册了");
            }
            msg = ValidateCodeTypes.Register.getMessage();
        } else if (type == ValidateCodeTypes.ResetPassword.getValue()) { // 重置密码
            // 验证手机号码是否已经注册
            if (!userService.isMobileRegistered(mobile)) {
                throw new BizException("该手机号码未注册");
            }
            msg = ValidateCodeTypes.ResetPassword.getMessage();
        }
        
        if (sendSms) {
            Random rnd = new Random();
            code = 100000 + rnd.nextInt(899999);
            
            msg = msg.replace("{code}", code + "");
            SmsService.send(mobile, msg);
        }
        
        validateCodeService.createOrReplace(mobile, code + "", type);
        
        return toJson("");
    }
    
}
